import setup_django

from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.utils import simplejson
from feedbag.apps.social.models import TwitterTweet, TwitterProfile
import datetime	
import sys
import time
import urllib2


def main():
	print 'cron main()'
	getTwitterTweetsJson()


def getTwitterTweetsJson():
	try:
		profiles = TwitterProfile.objects.all()
		
		TwitterTweet.objects.all().delete()
	
		for profile in profiles:
			url_info = urllib2.urlopen('http://api.twitter.com/1/statuses/user_timeline.json?screen_name='+profile.screen_name)
			
			if (url_info):
				json = simplejson.load(url_info)
			
				if (json):
					tweets = json 
					for tweet in tweets:
						uid = uid=tweet['id_str']
					
						try:
							TwitterTweet.objects.get(uid = uid)
						except TwitterTweet.DoesNotExist:
							ts = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(tweet['created_at'],'%a %b %d %H:%M:%S +0000 %Y'))
							TwitterTweet.objects.create(uid=uid, user_id=tweet['user']['id'], text=tweet['text'], screen_name=tweet['user']['screen_name'], created=ts)
			else:
				#getTwitterTweetsJson - Error! Getting URL		
				print ('getTwitterTweetsJson - Error! Getting URL')
		
	except TwitterProfile.DoesNotExist:
		raise Http404
	

if __name__ == "__main__":
	main()       